import socket, time

#Connect with telnet
#On linux: telnet localhost 5000
#or: telnet 192.168.1.8 5000 (if you connecting to a different machine)


#Port we wish to serve on
SERVER_PORT=5000

#create STREAMing socket (TCP)
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Bind to any/default interface on the local machine
serversocket.bind(("", SERVER_PORT))

#become a server socket
serversocket.listen(5)


#List of clients - fill this up as we go
clients=[]


#Set blocking to OFF.  Without threads, this is the only way we can
#deal with multiple users.  If blocking is ON, we will be stuck at the
#accept() funciton call until someone connects
serversocket.setblocking(0)

while True:
    try:
        #accept connections from outside. Note we get a new socket
        #object, leaving the original one free for more users to
        #connect
        (clientsocket, address) = serversocket.accept()
        #add it to the client list
        clients.append(clientsocket)
        #Set blocking to OFF.  Same as before, but this time we don't
        #want to block on the recv() call
        clientsocket.setblocking(0)
    except:
        #Non-blocking sockets throw an exception if asked to
        #connect/recieve when there's nothing to do.  They do this
        #rather than block.  We need to cope with that, so we catch
        #the exception and move on
        pass


    #Keep a list of messages ready to be sent
    messages=[]


    #See which clients have something to say
    for c in clients:
        try:
            #Catch the exception associated with non-blocking sockets again
            data=c.recv(1024)
            if data!="" and data != None:
                #If there is some data, put it into the queue
                messages.append(data)
        except:
            pass
        
    #Now we have a list of messages sent from clients since the last
    #time through the loop, we send each item to every client
    for c in clients:
        for m in messages:
            c.send(m)
    time.sleep(1)
